package org.hashdb.client.net.nio;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.hashdb.client.net.nio.msg.ErrorMessage;
import org.hashdb.client.net.nio.msg.Message;
import org.hashdb.client.net.nio.msg.MessageMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Date: 2024/1/18 18:36
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
interface ProtocolCodec {
    @Nullable Message<?> decode(ChannelHandlerContext ctx, ByteBuf in);

    @NotNull ByteBuf encode(ChannelHandlerContext ctx, Message<?> msg);

    @Nullable
    static MessageMeta resolveMessageMeta(ChannelHandlerContext ctx, ByteBuf in) {
        int code = in.readInt();
        var messageType = MessageMeta.resolve(code);
        if (messageType == null) {
            ctx.writeAndFlush(new ErrorMessage(0, "illegal message type '" + code + "'"));
            return null;
        }
        return messageType;
    }
}
